
def ACTION_CREATE_BRANCH = 'Create Branch'
def ACTION_ARC_DIFF = 'Arc Diff'
def ACTION_ARC_LAND = 'Arc Land'

pipeline {
    agent {
        docker {
            image 'im30/java-build:v6'
            args "-v /home/im30/.m2:/home/im30/.m2 -v /home/im30/.ssh:/home/im30/.ssh"
        }
    }
    parameters {
        string(name: 'Callsign', description: 'Repositories callsign')
        choice(name: 'Action', choices: [ACTION_CREATE_BRANCH, ACTION_ARC_DIFF, ACTION_ARC_LAND], description: 'Job Action')
        string(name: 'Branch', description: 'branch')
        string(name: 'Token', description: 'Phabricator token')
    }
    stages {
        stage('Create Branch') {
            when {
                expression { params.Action == ACTION_CREATE_BRANCH }
            }
            steps {
                git credentialsId: 'im30', url: "ssh://git@phab.gotoim30.com/diffusion/${params.Callsign}"
                sh "git checkout -b ${params.Branch}"
                sh "git push -u origin ${params.Branch}"
            }
        }
        stage('Arc land') {
            when {
                expression { params.Action == ACTION_ARC_LAND }
            }
            steps {
                // TODO 如何保证 merge 就是 review 的代码？后来再推呢？
                git credentialsId: 'im30',
                        branch: "${params.Branch}",
                        url: "ssh://git@phab.gotoim30.com/diffusion/${params.Callsign}"
                sh 'git fetch --all'
                sh 'git checkout release '
                sh "git merge --no-ff ${params.Branch}"
                sh 'mvn clean compile test'
                sh 'git push'
            }
        }
        stage('Arc diff') {
            when {
                expression { params.Action == ACTION_ARC_DIFF }
            }
            steps {
                git credentialsId: 'im30',
                        branch: "${params.Branch}",
                        url: "ssh://git@phab.gotoim30.com/diffusion/${params.Callsign}"
                sh "echo '{\"hosts\":{\"https://phab.gotoim30.com/api/\":{\"token\":\"${params.Token}\"}}}' > /home/im30/.arcrc"
                sh 'arc diff master --coverage --preview'
                // TODO echo url
            }
        }
    }
    post {
        always {
            deleteDir()
        }
    }
}